#include "A_Config.h"
#include "MiBand4/MiBand4.h"
const char *mibandAddress = MIBAND_ADDRESS;
uint8_t key[16] = MIBAND_KEY;

lv_obj_t *btn_connect;
bool connectReq;
bool sendNotifyReq;
bool sendReminderReq;
bool sendWeatherReq;
bool setTimeReq;
bool setAlarmReq;
bool WiFiReq;

miband_weather_icon_t band_weather_icon[] = {
    CLEAR_SKY,
    CLEAR_SKY,
    SCATTERED_CLOUDS,
    SCATTERED_CLOUDS,
    CLOUDY,
    MIST,
    MIST,
    MIST,
    LIGHT_RAIN,
    MEDIUM_RAIN,
    HEAVY_RAIN,
    EXTREME_RAIN,
    MIST,
    LIGHT_SNOW,
    MEDIUM_SNOW,
    HEAVY_SNOW,
    EXTREME_SNOW,
    WIND_AND_RAIN,
    WIND_AND_RAIN,
    WIND_AND_RAIN,
};

class appMiFit : public AppBase
{
private:
    /* data */
public:
    appMiFit()
    {
        name = "mifit";
        title = "小米运动";
        description = "小米运动app on ESP32（包括基本功能和小爱同学）";
        image = "\xEF\x8A\x93";
    }
    void setup();
    void loop();
    void destruct();
};

/*
void mifit_log(const char *format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    char str[512];
    vsprintf(str, format, argptr);
    lv_obj_add_state(txt_debug, LV_STATE_FOCUSED);
    lv_textarea_set_cursor_pos(txt_debug, LV_TEXTAREA_CURSOR_LAST);
    lv_textarea_add_text(txt_debug, str);
    va_end(argptr);
}
*/

void appMiFit::setup()
{
    LOCKLV();
    btn_connect = button(scr, "连接手环", 10, 0, &connectReq);
    button(scr, "发送通知", 10, 40, &sendNotifyReq);
    button(scr, "设置提醒", 10, 80, &sendReminderReq);
    button(scr, "同步时间", 10, 120, &setTimeReq);
    button(scr, "同步天气", 10, 160, &sendWeatherReq);
    button(scr, "设置闹钟", 10, 200, &setAlarmReq);
    button(scr, "连接WiFi", 160, 200, &WiFiReq);
    UNLOCKLV();
    miband.setMAC(mibandAddress);
    miband.setKey(key);
    miband.MIBAND_TCP_HOST = HOME_TCP_HOST;
    miband.MIBAND_TCP_PORT = HOME_TCP_PORT;
    miband.mallocVoiceMem();
    miband.init();
    hal.DoNotSleep = true;
}

void appMiFit::loop()
{

    if (hal.axpShortPress)
    {
        hal.axpShortPress = false;
        appManager.goBack();
        return;
    }
    if (WiFiReq)
    {
        WiFiReq = false;
        WiFiMgr.autoConnect();
    }
    if (connectReq)
    {
        connectReq = false;
        if (miband.connect())
        {
            lv_toast("连接成功");
            lv_obj_add_state(btn_connect, LV_STATE_DISABLED);
            connectReq = false;
        }
        else
        {
            lv_toast("连接失败");
        }
    }

    if (lv_obj_has_state(btn_connect, LV_STATE_DISABLED) == false)
        return;
    if (sendNotifyReq)
    {
        sendNotifyReq = false;
        String title, msg;
        title = msgbox_string("请输入标题", false, false, true);
        msg = msgbox_string("请输入内容", false, false, true);
        if (msgbox_yn("是否确认发送？") == false)
            return;
        miband.sendNotify(title.c_str(), msg.c_str(), WECHAT);
        lv_toast("消息通知已发送");
    }
    if (sendReminderReq)
    {
        sendReminderReq = false;
        uint8_t slot = msgbox_number("存储位置", 16, 0, 0);
        bool isDel = msgbox_yn("是否为删除此事件提醒？");
        if (isDel == false)
        {
            uint16_t time = msgbox_time("提醒时间");
            String msg = msgbox_string("提醒内容", false, false, true);
            if (msgbox_yn("是否确认发送？") == false)
                return;
            miband.setRemind(slot, hal.rtc.year, hal.rtc.month, hal.rtc.day, time / 60, time % 60, msg.c_str());
            return;
        }
        lv_toast("已删除事件提醒");
        miband.setRemind(slot, 0, 0, 0, 0, 0, "", 0);
    }
    if (sendWeatherReq)
    {
        sendWeatherReq = false;
        int8_t i;
        miband_weather_t bandweather[7];
        char weather_desc[7][40];
        weatherInfo24H *w = weather.getWeather(hal.rtc.month, hal.rtc.day, hal.rtc.hour);
        if (w == NULL)
        {

            lv_toast("天气信息不可用，请到主菜单更新天气");
            return;
        }
        for (i = 0;; ++i)
        {
            int16_t mintemp = 100, maxtemp = -100;
            uint8_t weathercon = 0;
            bool hasrain = false;
            int raintime = 0;
            int rainendtime = 0;
            uint8_t j;
            for (j = 0; j < 24; ++j)
            {
                if (i == 0 && j == 0)
                    j = hal.rtc.hour;
                if (w->rain > 0)
                {
                    if (hasrain == false)
                    {
                        raintime = j;
                        hasrain = true;
                    }
                    rainendtime = j;
                }
                if (w->temperature > maxtemp)
                    maxtemp = w->temperature;
                if (w->temperature < mintemp)
                    mintemp = w->temperature;
                if (w->weathernum > 2)
                    weathercon = w->weathernum;
                if (hasrain)
                    weathercon = 9;
                ++w;
                if (w >= weather.hour24 + 120)
                    break;
            }
            if (hasrain)
                sprintf(weather_desc[i], "%d点到%d点有雨", raintime, rainendtime);
            else
                strcpy(weather_desc[i], weather_names[weathercon]);
            bandweather[i].icon = band_weather_icon[weathercon];
            bandweather[i].maxTemp = maxtemp / 10;
            bandweather[i].minTemp = mintemp / 10;
            bandweather[i].weather_desc = weather_desc[i];
            if (j != 24)
                break;
        }
        DateTime dt1(hal.rtc.year, hal.rtc.month, hal.rtc.day, hal.rtc.hour, hal.rtc.minute, hal.rtc.sec);
        miband.setWeather(dt1.unixtime() - 3600 * 8, bandweather, i + 1);
        miband.setWeatherLocation("涿州一中");
        lv_toast("天气已推送");
    }
    if (setTimeReq)
    {
        setTimeReq = false;
        if (msgbox_yn("是否确认发送？") == false)
            return;
#ifdef RTC_IS_DS3231
        miband.setTime(hal.rtc.year, hal.rtc.month, hal.rtc.day, hal.rtc.weekday, hal.rtc.hour, hal.rtc.minute, hal.rtc.sec);
#else
        miband.setTime(hal.rtc.year, hal.rtc.month, hal.rtc.day, hal.rtc.weekday + 1, hal.rtc.hour, hal.rtc.minute, hal.rtc.sec);
#endif
    }
    if (setAlarmReq)
    {
        setAlarmReq = false;
        uint8_t slot = msgbox_number("输入存储位置", 6, 0, 0);
        bool del = msgbox_yn("是否删除闹钟");
        uint16_t time = 0;
        bool everyday = false;
        if (del == false)
        {
            time = msgbox_time("请输入闹钟时间");
            everyday = msgbox_yn("是否设置为每天");
            if (msgbox_yn("是否确认发送？") == false)
                return;
        }
        miband.setAlarm(slot, time / 60, time % 60, (everyday ? 0x7f : MIBAND_ALARM_REPEAT_ONCE) & (del ? 0 : 0xff));
        lv_toast("已设置闹钟");
    }
}

void appMiFit::destruct()
{
    miband.disconnect();
    ESP.restart();
    // 下面永远执行不到
    free(miband.voiceData);
    hal.DoNotSleep = false;
}

static appMiFit app;